package com.mu.websocket;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.mu.BigModelNew;
import com.mu.domain.MessageEntity;
import com.mu.manger.MessageCallBack;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

/**
 * @author EDY
 */
@Slf4j
public class XunListener extends WebSocketListener {

    public XunListener() {}

    public static final Gson gson = new Gson();
    @Override
    public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);

        MessageCallBack messageCallBack = MessageCallBack.getSingleton();
        MessageEntity messageEntity = MessageEntity.getSingleton();
        String userId = messageEntity.getUserIdByWebsocket(webSocket);
        if (myJsonParse.header.code != 0) {
            log.error("发生错误，错误码为：{} ", myJsonParse.header.code);
            log.error("本次请求的sid为：{} ", myJsonParse.header.sid);
            webSocket.close(1000, "");
        }
        List<Text> textList = myJsonParse.payload.choices.text;
        for (Text temp : textList) {
            messageCallBack.setBackMsg(userId, temp.content);
        }
        if (myJsonParse.header.status == 2) {
            // 可以关闭连接，释放资源
            log.info("接收消息完成，存储消息，释放资源，*************************************************************************************");
            messageCallBack.sendBack(userId);
            //TODO 只有关闭，没有超时关闭
            //TODO 关闭之后要清理数据
            webSocket.close(1000, "");
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (null != response) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                System.out.println("onFailure body:" + response.body().string());
                if (101 != code) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    class JsonParse {
        Header header;
        Payload payload;
    }

    class Header {
        int code;
        int status;
        String sid;
    }

    class Payload {
        Choices choices;
    }

    class Choices {
        List<Text> text;
    }

    class Text {
        String role;
        String content;
    }
}
